import * as path from 'path';
import { isExist, compareVersion, exec, send } from '../helper/utils';
import { IOptionsWithUrl } from '.';

export default async (repoPath: string, options: IOptionsWithUrl): Promise<void> => {
  const packageJsonPath = path.join(repoPath, './package.json');
  const exist = await isExist(packageJsonPath);

  if (exist) {
    const pkg = require(packageJsonPath);
    const dependencies = pkg.dependencies;
    let needInstall = false;
    for (const key in dependencies) {
      const filepath = path.join(repoPath, `./node_modules/${key}/package.json`);
      if (await isExist(filepath)) {
        const version = require(filepath).version;
        if (compareVersion(dependencies[key].version, version)) {
          needInstall = true;
          break;
        }
      } else {
        needInstall = true;
        break;
      }
    }

    if (needInstall) {
      try {
        send('正在安装依赖');
        const std = await exec('npm i', { cwd: repoPath });
        send(std.stderr);
        if (std.stdout) {
          send(std.stdout);
          let cmd = '';
          if (options.cmd) {
            cmd = options.cmd;
          } else if (pkg.scripts && pkg.scripts.restart) {
            cmd = pkg.scripts.restart;
          }
          if (cmd) {
            const std = await exec(cmd, { cwd: repoPath });
            send(std.stderr);
            send(std.stdout);
          }
        }
      } catch (err) {
        send(err, false);
      }
    } else {
      send('没有依赖需要安装或更新');
    }
  } else if (options.cmd) {
    const std = await exec(options.cmd, { cwd: repoPath });
    send(std.stderr);
    send(std.stdout);
  }
  send('EXIT');
};
